package Midium;

import java.util.Stack;

// 134.加油站
/*
 * 思：
 * 出发点只能选在gas[i]>=cost[i]的这些位置
 * 每次减去cost[i]如果为负数，则放弃本次循环
 * 如果为正数，则再加上gas[i+1]
 * */
public class Solution134 {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        Stack stack = new Stack();
        // 寻找合适的初始位置
        for (int i = 0; i < gas.length; i++) {
            if (gas[i] >= cost[i])
                stack.push(i);
        }
        // 开始判断栈里每一条路是否可以走一圈
        while (!stack.empty()) {
            int start = (int) stack.pop();
            int curGas = start == gas.length - 1 ? gas[0] : gas[start + 1];
            curGas += gas[start] - cost[start];
            int term = 0;
            start = start == gas.length - 1 ? 0 : start + 1;
            while (term < gas.length - 1) {
                curGas -= cost[start];
                if (curGas < 0) break;
                if (start == gas.length - 1) start = 0;
                else start++;
                curGas += gas[start];
                term++;
            }
            if (term == gas.length - 1) return start; // 正好回到原点
        }
        return -1;
    }
}
